package cc.wfu.domain.order.service;

import cc.common.types.entity.ProductActivityEntity;
import cc.common.types.valobj.ProductStateVO;
import cc.wfu.domain.order.model.aggregate.CreateOrderAggregate;
import cc.wfu.domain.order.model.entity.*;
import cc.wfu.domain.order.model.valobj.ActivitySkuStockKeyVO;
import cc.wfu.domain.order.model.valobj.OrderStateVO;
import cc.wfu.domain.order.model.valobj.PayStatusVO;
import cc.wfu.domain.order.repository.IProductActivityRepository;
import cc.wfu.domain.order.service.rule.factory.DefaultActivityChainFactory;
import cc.wfu.types.common.Constants;
import cc.wfu.types.exception.AppException;
import cc.wfu.types.snow.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc:
 * @Date: 2024-06-06-18:19
 */
@Slf4j
@Service
public class ProductActivityService extends AbstractProductActivity implements ISkuStock {

    /**
     * 下单 - 生成支付二维码
     * @param createOrderAggregate 订单信息
     * @return 支付二维码
     */
    @Override
    protected PayOrderEntity createOrder(CreateOrderAggregate createOrderAggregate) {
        // 0. 拿到userId
        String userId = createOrderAggregate.getUserId();
        // 1. 查询有效的未支付订单，如果存在直接返回 微信支付 Native CodeUrl
        UnpaidOrderEntity unpaidOrderEntity = activityRepository.queryUnpaidOrder(createOrderAggregate);
        if (null != unpaidOrderEntity && PayStatusVO.WAIT.equals(unpaidOrderEntity.getPayStatus())
                && null != unpaidOrderEntity.getPayUrl()) {
            log.info("创建订单-存在，已生成微信支付，返回 userId: {} orderId: {} payUrl: {}", userId, unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getPayUrl());
            return PayOrderEntity.builder().userId(userId).orderId(unpaidOrderEntity.getOrderId()).payUrl(unpaidOrderEntity.getPayUrl()).payStatus(unpaidOrderEntity.getPayStatus()).build();
        } else if (null != unpaidOrderEntity && null == unpaidOrderEntity.getPayUrl()) {
            log.info("创建订单-存在，未生成微信支付 userId: {} orderId: {}", userId, unpaidOrderEntity.getOrderId());
            PayOrderEntity payOrderEntity = doPersonalPrepayOrder(userId, unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getProductName(), unpaidOrderEntity.getTotalAmount().toString());
            if (payOrderEntity == null) {
                log.error("创建订单-失败, 支付单生成失败");
                throw new AppException("创建订单-失败, 支付单生成失败");
            }
            log.info("创建订单-完成，生成支付单。userId: {} orderId: {} payUrl: {}", userId, payOrderEntity.getOrderId(), payOrderEntity.getPayUrl());
            return payOrderEntity;
        }
        // 2. 没有未支付订单，开始生成订单
        log.info("创建订单-不存在有效的未支付订单，开始创建点单，返回 userId: {}", userId);
        // 2.1 保存订单
        activityRepository.doSaveOrder(createOrderAggregate);
        // 2.2 创建支付单 - 生成支付 url
        ProductOrderEntity productOrderEntity = createOrderAggregate.getProductOrderEntity();
        PayOrderEntity payOrderEntity = doPersonalPrepayOrder(userId, productOrderEntity.getOrderId(), productOrderEntity.getProductName(), productOrderEntity.getTotalAmount().toString());
        if (payOrderEntity == null) {
            log.error("创建订单-失败, 支付单生成失败...");
            throw new AppException("创建订单-失败, 支付单生成失败...");
        }
        log.info("创建订单-完成，生成支付单。userId: {} orderId: {} payUrl: {}", userId, productOrderEntity.getOrderId(), payOrderEntity.getPayUrl());
        return payOrderEntity;
    }




    /**
     * 创建订单聚合对象
     * @param skuRechargeEntity sku下单实体
     * @param activitySkuEntity sku订单实体
     * @param activityEntity 活动实体
     * // @param activityCountEntity 次数配置实体
     * @return 订单聚合对象
     */
    @Override
    protected CreateOrderAggregate buildOrderAggregate(SkuRechargeOrderEntity skuRechargeEntity, ProductActivitySkuEntity activitySkuEntity, ProductActivityEntity activityEntity) {
        ProductOrderEntity productOrderEntity = ProductOrderEntity.builder()
                .sku(skuRechargeEntity.getSku())
                .userId(skuRechargeEntity.getUserId())
                .productId(activityEntity.getProductId())
                .productName(activityEntity.getProductName())
                .orderId(String.valueOf(snowflakeIdGenerator.nextId()))
                .totalAmount(skuRechargeEntity.getTotalAmount())
                .orderTime(LocalDateTime.now())
                .state(OrderStateVO.completed)
                .outBusinessNo(skuRechargeEntity.getOutBusinessNo())
                .build();

        return CreateOrderAggregate.builder()
                .userId(skuRechargeEntity.getUserId())
                .productId(activityEntity.getProductId())
                .productOrderEntity(productOrderEntity)
                .build();
    }

    /**
     * 获取活动sku库存消耗队列
     *
     * @return 奖品库存Key信息
     * @throws InterruptedException 异常
     */
    @Override
    public ActivitySkuStockKeyVO takeQueueValue() throws InterruptedException {
        return activityRepository.takeQueueValue();
    }

    /**
     * 清空商品sku库存
     * @param sku sku
     */
    @Override
    public void clearActivitySkuStock(Long sku) {
        activityRepository.clearActivitySkuStock(sku);
    }

    /**
     * 延迟队列 + 任务 趋势更新活动sku库存
     *
     * @param sku 活动商品
     */
    @Override
    public void updateActivitySkuStock(Long sku) {
        activityRepository.updateActivitySkuStock(sku);
    }

    /**
     * 支付成功 - 更新订单信息
     */
    @Override
    public boolean changeOrderPaySuccess(String outTradeNo, String payNo, BigDecimal divide, Date parse) {
        return false;
    }
}
